<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!--朔源产品数据-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="queryParams.productName" placeholder="请输入产品名称" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="产品编码" prop="productCode">
            <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="产品条码" prop="productBarcode">
            <el-input v-model="queryParams.productBarcode" placeholder="请输入产品条码" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="产品分类" prop="productCategoryName">
            <el-input v-model="queryParams.productCategoryName" placeholder="请输入产品分类" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="产品状态" prop="statusCode">
            <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" v-hasPermi="['saveTrackingProduct']"   icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateTrackingProduct']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteTrackingProduct']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="queryTrackingProductPageResList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="产品名称" align="left" prop="productName"/>
          <el-table-column label="产品主图" align="center" prop="productImg" width="250">
            <template slot-scope="scope">
              <img width="100" height="100" :src="scope.row.productImg"/>
            </template>
          </el-table-column>
          <el-table-column label="产品编码" align="left" prop="productCode" width="200" />
          <el-table-column label="产品条码" align="left" prop="productBarcode" width="200" />
          <el-table-column label="产品状态" align="left" prop="statusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品分类" align="left" prop="productCategoryName" width="200" />
          <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateTrackingProduct']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteTrackingProduct']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="queryTrackingProductPageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">

        <el-form-item label="产品名称" prop="productName">
          <el-input autocomplete="off" v-model="form.productName" placeholder="请输入产品名称" maxlength="20" />
        </el-form-item>

        <el-form-item label="产品分类" prop="productCategoryId">
          <el-select :hide-required-asterisk="true" v-model="form.productCategoryId" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in productCategoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="产品主图" prop="productImg" ref="productImg">
          <el-upload
            ref="image"
            class="avatar-uploader"
            action="#"
            accept="image/jpeg,image/gif,image/png,image/jpg"
            :show-file-list="false"
            :http-request="requestUpload"><!--覆盖默认上传-->
            <img v-if="form.productImg" :src="form.productImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>


        <el-form-item label="产品编码" prop="productCode">
          <el-input autocomplete="off" v-model="form.productCode" placeholder="请输入产品编码" maxlength="20" />
        </el-form-item>

        <el-form-item label="产品条码" prop="productBarcode">
          <el-input autocomplete="off" v-model="form.productBarcode" placeholder="请输入产品条码" maxlength="20" />
        </el-form-item>

        <el-form-item label="产品状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="form.statusCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="产品描述" prop="description">
          <vue-ueditor-wrap v-model="form.description" :config="myConfig"></vue-ueditor-wrap>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number :hide-required-asterisk="true" v-model="form.sort" :min="1" :max="10000" label="排序" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { baiDuUeditor } from '@/utils/ueditorConfig'
  import VueUeditorWrap from "vue-ueditor-wrap"; // ES6 Module
  import {queryTrackingProductPageResList, saveTrackingProduct, updateTrackingProduct, deleteTrackingProductByProductId} from '@/api/tracking/trackingProduct'
  import {querySelectNormalTrackingProductCategoryResList } from '@/api/tracking/trackingProductCategory'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  import { imageSingleUpload } from '@/api/common/fileUpload'

  //默认查询参数
  let defaultQueryParams = {
    productName: undefined,
    productCode: undefined,
    productBarcode: undefined,
    productCategoryName: undefined,
    productNumber: undefined,
    startTime: undefined,
    endTime: undefined,
    statusCode: "",
    page: 1,
    rows: 10
  }
  export default {
    name: "trackingProductAdmin",
    components: {
      VueUeditorWrap
    },
    data() {
      return {
        // ueditor
        myConfig: baiDuUeditor(350),
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 朔源产品状态
        statusOptions: [],
        //产品分类选项
        productCategoryOptions: [],
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        // 新增修改表单校验
        addUpdateOpenRules: {
          productName: [
            { required: true, message: "产品名称不能为空"},
          ],

          productCategoryId: [
            { required: true, message: "产品分类必须选择"},
          ],
          productImg: [
            { required: true, message: "产品主图必须上传"},
          ],

          productCode: [
            { required: true, message: "产品编码不能为空"},
          ],
          productBarcode: [
            { required: true, message: "产品条码不能为空"},
          ],
          statusCode: [
            { required: true, message: "分类状态必须选择"}
          ],
          description: [
            { required: true, message: "产品描述不能为空"},
          ],
          sort: [
            { required: true, message: "排序不能为空",trigger: "blur" },
          ]
        },
      }
    },
    created() {
      this.queryTrackingProductPageResList();
      this.initDict();
    },
    methods: {
      //获取数据字典
      initDict(){
        let dictArr = ["PRODUCT_SALE_STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['PRODUCT_SALE_STATUS']));
        });
      },

      //上传产品主图
      requestUpload(file) {
        const dataForm = new FormData()
        dataForm.append('file', file.file)
        imageSingleUpload(dataForm).then(result => {
          if(result.errorCode===0){
            this.form.productImg = result.data.fileAbsolutePath;
            this.$refs["productImg"].clearValidate()
          }else{
            this.$message.error(result.message)
          }
        })
      },

      /** 产品分类查询 */
      querySelectNormalTrackingProductCategoryResList() {
        querySelectNormalTrackingProductCategoryResList({}).then(response => {
          this.productCategoryOptions = response.data;
        });
      },

      /** 查询朔源产品列表 */
      queryTrackingProductPageResList() {
        this.loading = true
        queryTrackingProductPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.productId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryTrackingProductPageResList()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.querySelectNormalTrackingProductCategoryResList();
        this.addUpdateOpen = true;
        this.title = "添加溯源产品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.querySelectNormalTrackingProductCategoryResList();
        this.addUpdateOpen = true;
        this.title = "修改溯源产品";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选溯源产品?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const productId={productId:row.productId}
          return deleteTrackingProductByProductId(productId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryTrackingProductPageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.productId !== undefined) {
              updateTrackingProduct(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTrackingProductPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveTrackingProduct(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTrackingProductPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryTrackingProductPageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          productId:undefined,
          productCategoryId: undefined,
          productName: undefined,
          productBarcode: undefined,
          productCode: undefined,
          remark: undefined,
          productImg: undefined,
          description: undefined,
          sort: 1,
          statusCode: "",
          statusOptions: []
        };
        this.resetForm('form')
      }
    }
  }
</script>
<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    line-height: 150px;
    display: block;
  }
</style>
